package com.wgo.bpot.common.transport.util;

import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.wgo.bpot.common.transport.exception.RematoException;

/**
 * @author PEide3
 */
public class ReflectionHelper {

	private static final transient Logger log = Logger.getLogger(ReflectionHelper.class.getName());

	@SuppressWarnings("unchecked")
	public static <T extends Object> T invokeMethod(Object instance, Method method, Object... args) {
		Assert.assertNotNull(instance, "The target instance of the invokation can not be null");
		Assert.assertNotNull(method, "The method to be invoked can not be null.");
		T result = null;
		try {
			result = (T)method.invoke(instance, args);
		} catch (Exception e) {
			String message = "Could not invoke method " 
				+ method.getName() + " on type " 
				+ instance.getClass().getSimpleName() + ", # parameters: " ;
			if (null != args) {
				message += args.length;
			} else {
				message += "'null'";
			}
			log.log(Level.SEVERE, message, e);
			log.info("args = " + args);
			throw new RematoException(message, e);
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	public static <T> Class<T> loadClass(String className) throws ClassNotFoundException {
		ClassLoader loader = Thread.currentThread().getContextClassLoader();

		if (loader != null) {
			return (Class<T>) Class.forName(className, false, loader);
		}
		return (Class<T>)Class.forName(className);
	}
	
	private ReflectionHelper () {}
}
